package com.gateway.enter.controller;

import com.gateway.enter.entity.Student;
import com.gateway.enter.service.StudentService;
import com.gateway.enter.util.MailClient;
import com.gateway.enter.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import java.util.Map;

/**
 * @author KLC0422
 * @create 2021-12-26- 10:07
 */
@Controller
public class RegisterController {

    @Autowired
    StudentService studentService;

    @Autowired
    TemplateEngine templateEngine;

    @Value("${spring.mail.to1}")
    private String to1;

    @Value("${spring.mail.to2}")
    private String to2;

    @Autowired
    MailClient mailClient;

    @GetMapping("/register")
    public String registerStudent(){
        return "site/register";
    }

    @PostMapping("/register")
    public String registerStudent(Student s2,Map<String,Object> map){
        String emailAddress = s2.getEmailAddress();
        String password = s2.getPassword();
        Student student = studentService.getStudentByEmailAddress(s2);
        if(student !=null){
            map.put("msg","用户已存在");
            return "site/error";
        }
        if(password.length()<8 || password.length()>16){
            map.put("msg","密码长度需要在8-16位");
            return "site/error";
        }
        Student newStudent = new Student();
        newStudent.setEmailAddress(emailAddress);
        String salt = PasswordUtil.randomSalt().toString().substring(0,3);
        password = PasswordUtil.password2Md5(password+salt);
        newStudent.setPassword(password);
        newStudent.setSalt(salt);
        studentService.insertStudent(newStudent);
        map.put("msg","注册成功，请联系管理员激活");

        Context context = new Context();
        context.setVariable("emailAddress",newStudent.getEmailAddress());
        String content = templateEngine.process("mail/activation",context);
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                mailClient.sendMail(to1,"激活账号",content);
            }
        };
        Thread thread1 = new Thread(r1);
        thread1.start();
        return "site/error";
    }


}


